package com.cloudknow.intface;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ObserverManager implements SubjectListener {
    private static ObserverManager observerManager;
    //观察者接口集合
    private List<ObserverListener> list = new ArrayList<>();

    /**
     * 单例
     */
    public static ObserverManager getInstance() {
        if (null == observerManager) {
            synchronized (ObserverManager.class) {
                if (null == observerManager) {
                    observerManager = new ObserverManager();
                }
            }
        }
        return observerManager;
    }

    /**
     * 加入监听队列
     */
    @Override
    public void add(ObserverListener observerListener) {
        list.add(observerListener);
    }

    /**
     * 通知观察者刷新数据
     */
    @Override
    public void notifyObserver(int type, String info, Object object) {
//        Collections.synchronizedList(list);

//        for (ObserverListener observerListener : list) {
//            if (list.size() == 0) {
//                return;
//            }
//
//            observerListener.observerUpData(type, info, object);
//        }


        List<ObserverListener> mlist = list;

//        for (ObserverListener observerListener : mlist) {
//            if (list.size() == 0) {
//                return;
//            }
//
//            observerListener.observerUpData(type, info, object);
//        }

        for (Iterator i =mlist.iterator(); i.hasNext();) {

            ObserverListener observerListener = (ObserverListener) i.next();
            observerListener.observerUpData(type, info, object);
        }

    }

    /**
     * 监听队列中移除
     */
    @Override
    public void remove(ObserverListener observerListener) {
        if (list.contains(observerListener)) {
            list.remove(observerListener);
        }
    }


    public static <T> List<T> copyIterator(Iterator<T> iter) {
        List<T> copy = new ArrayList<T>();
        while (iter.hasNext())
            copy.add(iter.next());
        return copy;
    }

}
